<template>
  <div class="app-container">
    <el-card v-show="showSearch" class="mb10" shadow="hover">
      <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="120px" size="small">
        <el-form-item label="等级名称" prop="params.name">
          <el-input
            v-model="queryParams.params.name"
            clearable
            placeholder="请输入等级名称"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item class="ml10">
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="hover">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['member:level:rule:add']"
            icon="el-icon-plus"
            plain
            size="mini"
            type="primary"
            @click="handleAdd"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['member:level:rule:edit']"
            :disabled="single"
            icon="el-icon-edit"
            plain
            size="mini"
            type="success"
            @click="handleUpdate"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['member:level:rule:remove']"
            :disabled="multiple"
            icon="el-icon-delete"
            plain
            size="mini"
            type="danger"
            @click="handleDelete"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['member:level:rule:export']"
            icon="el-icon-download"
            plain
            size="mini"
            type="warning"
            @click="handleExport"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="levelRuleList" border @sort-change="handleSortChange"
                @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column v-if="true" align="center" label="主键" prop="id" show-overflow-tooltip/>
        <el-table-column align="center" label="等级名称" prop="name" show-overflow-tooltip/>
        <el-table-column align="center" label="成长值" prop="minPoint" show-overflow-tooltip sortable/>
        <el-table-column align="center" label="专属会员价格" prop="memberPrice" show-overflow-tooltip sortable/>
        <el-table-column align="center" label="可用油品" prop="fuelsLimitName" show-overflow-tooltip/>
        <el-table-column align="center" label="创建人" prop="creatorName" show-overflow-tooltip/>
        <el-table-column align="center" label="创建时间" prop="createDate" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注信息" prop="remark" show-overflow-tooltip/>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                v-hasPermi="['member:level:rule:edit']"
                icon="el-icon-edit-outline"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"/>
            </el-tooltip>

            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['member:level:rule:remove']"
                icon="el-icon-delete"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="queryParams.pageSize"
        :page.sync="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改会员等级规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="1000px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="等级名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入等级名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成长值" prop="minPoint">
              <el-input-number v-model="form.minPoint" :min="0" controls-position="right" placeholder="请输入成长值"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专属优惠" prop="memberPrice">
              <el-input v-model="form.memberPrice" placeholder="请输入专属优惠（元/升）"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="可用油品：" prop="fuelsLimit">
              <el-checkbox-group v-model="checkFuelList">
                <el-checkbox v-for="item in fuelList" :key="item.id" :label="item.id+''">
                  {{ item.fuelName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入备注信息"
                        type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addLevelRule, getLevelRule, listLevelRule, updateLevelRule} from "@/api/member/levelRule";
import {formatDateTime, nowCnFormatDateTime} from "@/utils/date";
import {selectList as selectFuelList} from "@/api/base/fuel";

export default {
  name: "LevelRule",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员等级规则表格数据
      levelRuleList: [],
      checkFuelList: [],
      fuelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sortName: 'minPoint',
        sortOrder: 'asc',
        params: {
          name: undefined
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {
            required: true, message: "等级名称不能为空", trigger: "blur"
          }
        ],
        minPoint: [
          {
            required: true, message: "最小成长值不能为空", trigger: "blur"
          }
        ],
        memberPrice: [
          {
            required: true, message: "专属会员价格不能为空", trigger: "blur"
          }
        ],
        fuelsLimit: [
          {
            required: true, message: "可用油品不能为空", trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    selectFuelList().then(res => {
      this.fuelList = res.data;
    });
  },
  methods: {
    formatDateTime,
    /** 查询会员等级规则列表 */
    getList() {
      this.loading = true;
      listLevelRule(this.queryParams).then(response => {
        this.levelRuleList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        minPoint: undefined,
        memberPrice: undefined,
        fuelsLimit: undefined,
        creatorId: undefined,
        creatorName: undefined,
        createDate: undefined,
        modifierId: undefined,
        modifierName: undefined,
        modifiedDate: undefined,
        active: undefined,
        remark: undefined,
        version: undefined
      };
      this.resetForm("form");
      this.checkFuelList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.checkFuelList = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员等级规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getLevelRule(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.checkFuelList = this.form.fuelsLimit.split(',');
        this.open = true;
        this.title = "修改会员等级规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.fuelsLimit = this.checkFuelList.join(',')
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateLevelRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addLevelRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除会员等级规则编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delLevelRule(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/level/rule/export', {
        ...this.queryParams
      }, `levelRule_${nowCnFormatDateTime()}.xlsx`)
    }
  }
}

</script>

<style>
.el-form .el-select {
  width: 100%;
}
</style>
